package com.patrick.open.api.core.utils;

import javax.servlet.ServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

/**
 * @author patrick
 * @date 2020/5/29 4:33 下午
 * @Des 工具类
 * 最簡單的事是堅持，最難的事還是堅持
 */
public class HttpGetBody {
  /**
   * 获取请求Body
   *
   * @param request
   * @return
   */
  public static String getBodyString(ServletRequest request) {
    StringBuilder sb = new StringBuilder();
    BufferedReader reader = null;
    try {
      reader = new BufferedReader(new InputStreamReader(request.getInputStream(), Charset.forName("UTF-8")));
      String line = "";
      while ((line = reader.readLine()) != null) {
        sb.append(line);
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (reader != null) {
        try {
          reader.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    sb.trimToSize();
    return sb.toString();
  }
}
